/* eslint-disable import/no-extraneous-dependencies, consistent-return, no-console */
// 搭服务器
const express = require('express');
// 代理所需的包
const httpProxyMiddleware = require('http-proxy-middleware');
// 历史包
const historyApiFallback = require('connect-history-api-fallback');
// webpack包
const webpack = require('webpack');
// 中间件
const webpackDevMiddleware = require('webpack-dev-middleware');
// 热加载包
const webpackHotMiddleware = require('webpack-hot-middleware');

const webpackConfig = require('./build/webpack.dev');

const app = express();

// 托管静态文件
// app.use('/', express.static(join(__dirname, 'dist')));

// 设置端口
app.set('port', (process.env.PORT || 8080));

// 代理
app.use((req, res, next) => {
  if (req.headers.accept.includes('text') || req.url.includes('.')) {
    next();
  } else {
    return httpProxyMiddleware('/', {
      target: 'http://192.168.2.18:8098', // 接口的地址
      logLevel: 'error',
    })(req, res, next);
  }
});

app.use(historyApiFallback());

const compiler = webpack(webpackConfig);
app.use(webpackDevMiddleware(compiler, {
  stats: { colors: true, chunks: false },
  noInfo: true,
  publicPath: webpackConfig.output.publicPath,
}));
app.use(webpackHotMiddleware(compiler));

// 绑定并监听指定的主机和端口上的连接
app.listen(app.get('port'), (err) => {
  if (err) {
    console.log(err);
  } else {
    console.log(`Listening at http://localhost:${app.get('port')}`);
  }
});


